package com.bybops.ui.activity.account

import android.Manifest
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.support.v4.content.FileProvider
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.widget.PopupWindow
import baseproject.com.mybaseproject.mvp.presenter.SplashPresenterImpl
import baseproject.com.mybaseproject.net.FileDownLoadObserver
import baseproject.com.mybaseproject.net.FileUpOrDownloadUtils
import baseproject.com.mybaseproject.ui.base.BaseMvpActivity
import baseproject.com.mybaseproject.utils.ActivityUtils
import baseproject.com.mybaseproject.utils.NetworkUtil
import com.bybops.R
import com.bybops.app.AppConstant
import com.bybops.contract.SplashContract
import com.bybops.model.api.URLConstant
import com.bybops.model.bean.CheckVersion
import com.bybops.utils.AppUtils
import com.bybops.utils.FileUtils
import com.gyf.barlibrary.ImmersionBar.getStatusBarHeight
import kotlinx.android.synthetic.main.activity_splash.*
import kotlinx.android.synthetic.main.layout_apk_update.view.*
import java.io.File



/**
 * 启动页面
 */
class SplashActivity : BaseMvpActivity<SplashContract.SplashView, SplashPresenterImpl>(), SplashContract.SplashView {


    override var mPresenter: SplashPresenterImpl = SplashPresenterImpl()

    private var alphaAnimation: AlphaAnimation? = null
    private var popupWindow: PopupWindow? = null

    private var dialog: ProgressDialog? = null

    private var time = 0L

    override fun getLayoutId(): Int? {
        return R.layout.activity_splash
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        var intentFilter = IntentFilter()
        intentFilter.addAction(AppConstant.ACTION_STATUS_AUTH_FAIL)
        registerReceiver(mReceiver , intentFilter)
        initView()

    }
    private val mReceiver = object : BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == AppConstant.ACTION_STATUS_AUTH_FAIL){
                //token失效
                com.bybops.widget.AlertDialog(this@SplashActivity).builder()
                        .setGone()
                        .setTitle("令牌过期")
                        .setNegativeButton("取消", R.color.color_2c9cf0, null)
                        .setPositiveButton("重新登录", R.color.color_2c9cf0) {
                            //跳转到登录界面
                            ActivityUtils.startActivityAndFinish(this@SplashActivity , LoginActivity::class.java)
                        }
                        .show()
            }
        }
    }
    private fun initView() {
        time = System.currentTimeMillis()
        //渐变展示启动屏
        alphaAnimation = AlphaAnimation(0.3f, 1.0f)
        alphaAnimation?.duration = 2000
        alphaAnimation?.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationEnd(arg0: Animation) {
            }

            override fun onAnimationRepeat(animation: Animation) {}

            override fun onAnimationStart(animation: Animation) {}

        })

        checkPermission()
    }

    /**
     * 显示版本更新对话框
     */
    override fun showUpdateDialog(checkVersion: CheckVersion) {

        val popView = View.inflate(this, R.layout.layout_apk_update, null)
        popupWindow = PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true)
        popupWindow?.setBackgroundDrawable(ColorDrawable())
        popupWindow?.isFocusable = true
        popupWindow?.isOutsideTouchable = true

        popupWindow?.isOutsideTouchable = false
        popupWindow?.isClippingEnabled = false
        if (!TextUtils.isEmpty(checkVersion.newVer)) {
            popView.update_title_tv.text = "更新内容 (V${checkVersion.newVer})"
        } else {
            popView.update_title_tv.visibility = View.GONE
        }
        if (!TextUtils.isEmpty(checkVersion.newNote)) {
            popView.content_tv.text = checkVersion.newNote
        } else {
            popView.content_tv.visibility = View.GONE
        }
        popView.close_iv.setOnClickListener { mPresenter.autoLogin() }
        popView.update_tv.setOnClickListener {
            //判断是否是4G，是的话进行温馨提示的弹窗
            if (NetworkUtil.isWifi(this@SplashActivity)) {
                downloadNewApk(URLConstant.mApkDownload)
            } else {
                showRemindDialog(checkVersion)
            }
            popupWindow?.dismiss()
        }
        popupWindow?.showAtLocation(layoutSplash, Gravity.CENTER, 0,
                getStatusBarHeight(this))
    }

    /**
     * 流量提醒
     */
    private fun showRemindDialog(checkVersion: CheckVersion) {
        val alertDialog = AlertDialog.Builder(this@SplashActivity)
        alertDialog.setTitle("温馨提示").setMessage("当前为4G状态，是否继续下载更新")
                .setNegativeButton("取消"
                ) { dialog, which ->
                    when (checkVersion.ret) {
                        0 -> mPresenter.autoLogin()  //普通升及
                        -1 -> finish() //强制升级
                    }
                }.setPositiveButton("确定"
                ) { dialog, which ->

                    downloadNewApk(URLConstant.mApkDownload)
                }.create().show()
    }

    /**
     * 下载更新包
     */
    private fun downloadNewApk(downloadUrl: String) {
        //判断有没有存储权限
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            //如果没有存储权限
            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe {  granted ->
                        if (granted) {
                            // All requested permissions are granted
                            // 用户已经同意该权限
                            downloadNewApk(downloadUrl)
                        } else {
                            showToast("需要开启存储权限")
                        } }
        }
        val saveFilePath = File(AppConstant.DIR_TEMP + "cloudServer.apk")
        if (saveFilePath.exists()) {
            saveFilePath.delete()
            saveFilePath.createNewFile()
        }
        var sdCardRoot = FileUtils.getSDPath()

        if (TextUtils.isEmpty(sdCardRoot)) {
            showToast("没有SD卡")
            return
        }
        val savePath = File(sdCardRoot + AppConstant.DIR_TEMP)
        if (!savePath.exists()) {
            savePath.mkdirs()
        }
        FileUpOrDownloadUtils.downloadFile(downloadUrl, saveFilePath.absolutePath, object : FileDownLoadObserver<File>() {
            override fun onDownLoadBefore() {
                dialog = ProgressDialog(this@SplashActivity)
                dialog?.setTitle("下载进度")
                dialog?.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
            }

            override fun onDownLoadSuccess(file: File) {
                dialog?.dismiss()
                showToast("下载成功： " + file.absoluteFile)
                installApk(file)
            }

            override fun onDownLoadFail(throwable: Throwable) {
                dialog?.dismiss()
            }

            override fun onProgress(progress: Int, total: Long) {
                val all = (total / 1024 / 1024).toFloat()
                val sumPercent = progress * total
                val percent = sumPercent / 1024f / 1024f
                dialog?.setProgressNumberFormat(String.format(
                        "%.2fM/%.2fM", percent, all))
                dialog?.max = 100
                dialog?.progress = (100 * progress)
                dialog?.show()
            }
        })
    }

    private fun installApk(file: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        val data: Uri
        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // "com.cloud.server.fileprovider"即是在清单文件中配置的authorities
            data = FileProvider.getUriForFile(this, AppUtils.getPackageName(this) + ".fileprovider", file)
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        } else {
            data = Uri.fromFile(file)
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive")
        startActivity(intent)
        finish()
    }


    /**
     * 路由跳转
     */
    override fun redirectTo(clazz : Class<*>) {
        var useTime = System.currentTimeMillis() - time
        var delayTime = if (useTime > 2000) 0 else (2000 - useTime)
        Handler().postDelayed({ ActivityUtils.startActivityAndFinish(this, clazz) }, delayTime)
    }

    /**
     * 申请权限
     */
    private fun checkPermission() {
        //申请权限
        rxPermissions.request(
//                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.READ_CALENDAR,
//                Manifest.permission.READ_CALL_LOG,
//                Manifest.permission.READ_CONTACTS,
                Manifest.permission.READ_PHONE_STATE,
//                Manifest.permission.READ_SMS,
//                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA
//                Manifest.permission.CALL_PHONE,
//                Manifest.permission.SEND_SMS
                    )
                .subscribe { granted ->
                    if (granted) {
                        // All requested permissions are granted
                        // 用户已经同意该权限
                        layoutSplash.startAnimation(alphaAnimation)
                        //获取配置文件
                        mPresenter.checkUpdateInfo()
//                        redirectTo()
                    } else {
                        // At least one permission is denied
                        //关闭数据库
                        //关闭所有页面
                        ActivityUtils.removeAllActivitys()
                        //退出应用程序
                        System.exit(0)
                    }
                }
    }
}